package week_4;
// MyLinkedList
// auteur: J.Kaldeway

class ListNode<E>
{
    E data_;
    ListNode<E> next_;
        
    ListNode(E data, ListNode<E> next)
    {
        data_ = data;
        next_ = next;
    }
        
    public String toString()
    {
        return data_.toString();
    }
}

public class MyLinkedList<E>
{
    private ListNode<E> head_ = null;
    private ListNode<E> tail_ = null;
    
    public void addLast(E e)
    {
        if (head_ == null)
        {
            head_ = new ListNode<E>(e,null);
            tail_ = head_;
        }
        else
        {
            ListNode<E> n = new ListNode<E>(e,null);
            tail_.next_ = n;
            tail_ = tail_.next_;
        }
    }
        
    public void delete(E e)
    {
        if (head_ != null)
        {
            if (head_.data_.equals(e))
            {
              	head_ = head_.next_;
              	if (head_ == null) tail_ = null;
            }
            else 
            {
            	ListNode<E> current = head_;
                while (current.next_ != null && !current.next_.data_.equals(e))
                    current = current.next_;
                if (current.next_ != null)
                    current.next_ = current.next_.next_; 
                if (current.next_ == null)
                   tail_ = current;
            }
        }
    }

    @Override
	public String toString()
    {
        String s = "";
        
        ListNode<E> current = head_;
        if (current != null)
        {
           s = s + current.toString();
           current = current.next_;
        }
        while (current != null)
        {
           s = s + " -> " + current.toString();
           current = current.next_; 
        } 
        return s;
    }
    
    public static void main(String[] s)
    {
        MyLinkedList<Integer> list = new MyLinkedList<Integer>();
        System.out.println(list);
        list.addLast(1);
        list.addLast(2);
        list.addLast(3);
        list.addLast(4);
        list.addLast(5);
        System.out.println(list);
        list.delete(5);
        System.out.println(list);
        list.delete(3);
        System.out.println(list);
        list.delete(1);
        System.out.println(list);
    }
}